﻿<%@ Page Language="C#" CodeBehind="~/Login.aspx.cs" MasterPageFile="~/MasterPage.master" Title="Login" %>

<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="UserManagementWCFService" %>
<%@ Import Namespace="UserManagementService" %>
<%@ Import Namespace="SolverLibrary.Data_Entities" %>
<script runat="server">
    private const string USERNAME_IDENTIFIER = "username";
    
    private const string COOKIE_IDENTIFIER = "CookieIdentifier";
    
    
    protected void SignInButton_Click(object sender, EventArgs e)
    {
        EncryptionService.ServiceClient encryptionClient = new EncryptionService.ServiceClient();
        //Get the inputs. If we don't have a valid one then alert.
        if (completeInputs())
        {
            User user = getUser(UsernameText.Value);
            if (user != null && user.Password.Equals(encryptionClient.Encrypt(PasswordText.Value)))
            {
                if (StaySignedInCheckbox.Checked)
                {
                    //Store the user information in our session.
                    storeInSession(user);
                    //Store the user information in a cookie for the next
                    //time we access the web site.
                    storeInCookies(user);
                }
                FormsAuthentication.RedirectFromLoginPage(user.Username, false);
            }
            else
            {
                PasswordError.InnerText = "Invalid credentials.";
            }
        }

        encryptionClient.Close();
    }

    private void storeInCookies(User user)
    {
        FormsAuthentication.SetAuthCookie(user.Username, false);
        HttpCookie userCookie = Request.Cookies[ConfigurationManager.AppSettings[COOKIE_IDENTIFIER]];
        if (userCookie == null || userCookie[USERNAME_IDENTIFIER].Equals(""))
        {
            HttpCookie newCookie = new HttpCookie(ConfigurationManager.AppSettings[COOKIE_IDENTIFIER]);
            newCookie[USERNAME_IDENTIFIER] = user.Username;
            newCookie.Expires = DateTime.Now.AddMonths(2);
            Response.Cookies.Add(newCookie);      
        }
    }
    
    private void storeInSession(User user)
    {
        Session[ConfigurationManager.AppSettings[COOKIE_IDENTIFIER]] = user;
    }

    /// <summary>
    /// Get the user given the username.
    /// </summary>
    /// <param name="username">String username.</param>
    /// <returns></returns>
    private User getUser(string username)
    {
        UserManagementServiceClient client = new UserManagementServiceClient();
        User user = client.getUser(username);
        client.Close();
        return user;
    }

    private bool completeInputs()
    {
        string username = UsernameText.Value;
        string password = PasswordText.Value;
        if (username.Equals(""))
        {
            UsernameError.InnerText = "Please enter username.";
        }
        else
        {
            UsernameError.InnerText = "";
        }
        if (password.Equals(""))
        {
            PasswordError.InnerText = "Please enter password.";
        }
        else
        {
            PasswordError.InnerText = "";
        }
        return (!password.Equals("") && !username.Equals(""));
    }
</script>


<asp:Content ID="Content1" ContentPlaceHolderID="Body" runat="Server">
    <!-- Script to change the login button to enabled. -->
    <script>
        window.onload =
            function () {
                document.getElementById("loginNavigator").setAttribute("class", "active");
            }
    </script>
    Sign In
    <br />
    <br />
    <table>
        <tr>
            <td style="width: 78px">Username: </td>
            <td style="width: 137px">&nbsp;</td>
        </tr>
        <tr>
            <td colspan="2" style="height: 30px">
                <input id="UsernameText" type="text" runat="server" style="width: 208px" />
            </td>
        </tr>
        <tr>
            <td colspan="2" style="height: 30px">
                <p id="UsernameError" runat="server" style="color: red" />
            </td>
        </tr>
        <tr>
            <td style="width: 78px">Password:</td>
            <td style="width: 137px">&nbsp;</td>
        </tr>
        <tr>
            <td colspan="2" style="height: 26px">
                <input id="PasswordText" type="password" style="width: 208px" runat="server" /></td>
        </tr>
        <tr>
            <td colspan="2" style="height: 26px">
                <p id="PasswordError" runat="server" style="color: red" />
            </td>
        </tr>
        <tr>
            <td style="height: 26px">&nbsp;</td>
            <td style="height: 26px">&nbsp;</td>
        </tr>
        <tr>
            <td style="height: 26px">
                <asp:Button ID="SignInButton" runat="server" Text="Sign In" OnClick="SignInButton_Click" />
            </td>
            <td style="height: 26px">
                <input id="StaySignedInCheckbox" type="checkbox" runat="server" checked="checked" />
                Stay Signed In</td>
        </tr>
    </table>
    <br />
    <a href="<%= ConfigurationManager.AppSettings["BasePath"] + "CreateUser.aspx" %>" style="width: 162px">Create New User...</a>
</asp:Content>
